package torres.fileIO;

import java.io.File;
import java.io.ObjectOutputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.EOFException;
import java.util.ArrayList;
import java.util.List;

import torres.map.Map;
import torres.map.World;

/**
 * @author Torres
 * Handles all of the logic necessary for loading and saving 
 * to/from an external file. 
 */
public class Saver {
	
	/**
	 * Save the game to the specified file.
	 * @param name The name of this file to which the game is saved.
	 */
	public static void save(String name) {
		List<Map> mapList = World.getInstance().getMapList();
		
		Map currentMap = World.getInstance().getCurrentMap();
		FileOutputStream fileOS;
		ObjectOutputStream objectOS;
		String filename = "src/resources/savedData/";
		File file = new File(filename+name);
		
		try {
			fileOS = new FileOutputStream(file);
			objectOS = new ObjectOutputStream(fileOS);
			objectOS.writeObject(currentMap);
			for(Map  map : mapList ) {
				if(!map.equals(currentMap))
					objectOS.writeObject(map);
			}
			fileOS.close();
			objectOS.close();
		} catch(IOException exception) {exception.printStackTrace();}
		
	}
	
	/** 
	 * Load the game from the specified file.
	 * @param name The name of the file from which the game is loaded.
	 * @throws IOException If the specified save file cannot be read.
	 * @throws ClassNotFoundException If the specified save file is invalid.
	 */
	public static void load(String name) throws IOException , ClassNotFoundException {
		
		FileInputStream fileIN;
		ObjectInputStream objectIN;
		String filename = "src/resources/savedData/";
		ArrayList<Map> mapList = new ArrayList<Map>();
		
		try {
			fileIN = new FileInputStream(filename+name);
			objectIN = new ObjectInputStream(fileIN);
			Map map = (Map)objectIN.readObject();
			World.getInstance().setCurrentMap(map);
			while(map != null) {
				mapList.add(map);
				map = (Map)objectIN.readObject();
			}
			//fileIN.close();
			objectIN.close();
			
		} catch(EOFException exception) {  System.out.println("Reached end of save file"); }
		//  catch(IOException exception) { exception.printStackTrace(); }
		//  catch (ClassNotFoundException e) { e.printStackTrace(); }
		finally { World.getInstance().setMapList(mapList); }
	}
	
}
